#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/image.hpp"
#include "std_msgs/msg/string.hpp"
#include "std_msgs/msg/u_int32.hpp"
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include <opencv2/highgui.hpp>

using std::placeholders::_1;
using std::placeholders::_2;
using namespace std::chrono_literals;

class my_publisher: public rclcpp::Node
{
    private:
        std::string image_dir;
        sensor_msgs::msg::Image image;
        rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr pub_image;

        rclcpp::Subscription<std_msgs::msg::UInt32>::SharedPtr sub_bonus;
        
        int count = 0;
        // const int time_period = 5;
        rclcpp::TimerBase::SharedPtr timer;

        void timer_callback()
        {
            image.header.stamp = this->now();

            pub_image->publish(image);
            count++;
            RCLCPP_INFO(this->get_logger(), "I have published %d photos of cxk.", count);
        }
    
    public:
        my_publisher(std::string name): Node(name)
        {
            RCLCPP_INFO(this->get_logger(), "%s has been created successfully.", name.c_str());
            image_dir = "photo/cxk.png";

            pub_image = this->create_publisher<sensor_msgs::msg::Image>("image_cxk", 10);
            /*
            CvBridge是一个ROS库，提供ROS和OpenCV之间的接口
            */
            //load image and transform into msg
            cv::Mat img = cv::imread(image_dir, cv::IMREAD_UNCHANGED);
            cv_bridge::CvImage(std_msgs::msg::Header(), "rgb8", img).toImageMsg(image);

            timer = this->create_wall_timer(3s, std::bind(&my_publisher::timer_callback, this));

            //get bonus from the subscriber
            sub_bonus = this->create_subscription<std_msgs::msg::UInt32>("organizer", 10, std::bind(&my_publisher::bonus_callback, this, _1));
        }
        void bonus_callback(const std_msgs::msg::UInt32::SharedPtr msg)
        {
            RCLCPP_INFO(this->get_logger(), "cxk get %d dollars from the organizer. I will keep on fighting", msg->data);
        }
};

int main(int argc, char *argv[])
{
    rclcpp::init(argc, argv);
    auto node = std::make_shared<my_publisher>("one_publisher");
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}
